package juc.executors;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author 夏焰波
 * @date 2020-07-06 2:46
 */
public class CompletableFutureExample3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //CompletableFuture<String> stringFuture = CompletableFuture.supplyAsync(() -> "hello");
        //CompletableFuture<String> Future2 = stringFuture.whenComplete((v, t) -> {
        //    System.out.println("===");
        //    timeSleep(2);
        //    System.out.println("done");
        //});
        //System.out.println(">>" + Future2.get());

        /**
         * 应该先输出hello，但测试的whenCompleteAsync还是会阻塞，是否跟jsk版本有关？
         */
        //CompletableFuture<String> Future3 = stringFuture.whenCompleteAsync(
        //        (v, t) -> {
        //            System.out.println("===");
        //            timeSleep(2);
        //            System.out.println("done");
        //        });
        //System.out.println(">>" + Future3.get());
        //
        //Thread.currentThread().join();

        //CompletableFuture<Integer> future4 = stringFuture.thenApply(String::length);
        //System.out.println(">>" + future4.get());

        //CompletableFuture<Integer> future5 = stringFuture.thenApplyAsync(
        //        s -> {
        //            System.out.println("===");
        //            timeSleep(2);
        //            System.out.println("done");
        //            return s.length();
        //        });
        //System.out.println(">>" + future5.get());

        //CompletableFuture<Integer> future = CompletableFuture.supplyAsync(
        //        //需要强转
        //        (Supplier<String>) () -> {
        //            throw new RuntimeException("not get the data");
        //        }).handleAsync((s, t) -> {
        //    Optional.of(t).ifPresent(e -> System.out.println("Error"));
        //    return (s == null) ? 0 : s.length();
        //});
        //System.out.println(">>" + future.get());

        //CompletableFuture.supplyAsync(() -> "hello").toCompletableFuture();

        //CompletableFuture.supplyAsync(() -> "hello").thenAccept(System.out::println);

        CompletableFuture.supplyAsync(() -> "hello").thenRun(()-> System.out.println("done"));


    }

    /**
     * sleep the specify seconds
     */
    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
